package com.auto.base.controller;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.auto.base.pojo.AccessToken;
import com.auto.base.pojo.AccessTokenExample.Criteria;
import com.auto.base.pojo.SysUser;
import com.auto.base.service.AccessTokenService;
import com.auto.common.BaseController;
import com.auto.common.SessionInfo;
import com.auto.util.SystemUtil;
import com.base.callback.UrExcelCallBack;
import com.base.common.CommonConstants;
import com.base.common.DataTableNormalDatagrid;
import com.base.common.Datagrid;
import com.base.common.NormalDatagrid;
import com.base.common.RequestParameters;
import com.base.model.interfaze.FieldAppendArray;
import com.base.model.interfaze.MapperCallBackAdapter;
import com.base.service.UrExcelOptionService;
import com.base.util.JUtil;
import com.base.util.MapperUtil;
import com.base.util.Page;



//导入自动注入类型

@Controller
@RequestMapping("/sys/AccessToken")
public class AccessTokenController extends BaseController {

	private final Logger log = LoggerFactory.getLogger(AccessTokenController.class);
	@Resource
	private AccessTokenService service;
	@Resource
	protected UrExcelOptionService urExcelOptionService;
	private static final String templateFile = "/save/excel/output/AccessTokenModel.xls";
	private static final String templateModelFile = "/save/excel/input/AccessTokenModel.xls";

	/**
	 * 新增和修改
	 * @param record
	 * @return
	 */
	@RequestMapping(value = "addOrUpdate")
	@ResponseBody
	public Object addOrUpdate( @ModelAttribute AccessToken  record,HttpServletRequest request) {
		try {
			if(null == record){
				return setFail("接收数据为空！");
			}
			SysUser sysUser = getLoginSysUser(request);
			if(JUtil.isNULL(record.getUserId())) {
				//record.setLastUpdateUser(sysUser.getId());
				this.service.insertAccessToken(record);
				return setSuccess("添加成功!");
			} 
			//record.setLastUpdateUser(sysUser.getId());
			this.service.modifyAccessTokenByPkSelective(record);
			return setSuccess("修改成功!");
		}catch(Exception e){
			log.error(e.getMessage(), e);
			return setFail("处理异常!");
		}
	}


	/**
	 * 根据代理bean查询集合
	 * @return
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public Object list(@ModelAttribute final RequestParameters requestParameters,HttpServletRequest request) {
		try {
			FieldAppendArray appendArray = new FieldAppendArray();
			AccessToken rec = new AccessToken();
			Page paging = null;
			if(requestParameters.getIsNonPage()==0){
			if(requestParameters.getComp() == 1){
				 paging = Page.getInstance(requestParameters.getPage()-1,requestParameters.getRows());
			}else{
				 paging = Page.getInstance_(requestParameters.getiDisplayStart(),requestParameters.getiDisplayLength());
			}
			}
			String sort = requestParameters.getSort();
			if(requestParameters.getComp() != 1){
				if(null != requestParameters.getiSortCol_0()){
				  int column = JUtil.strToInt(requestParameters.getiSortCol_0(), 0);
				  if(column < 0){
					  column = 0;
				  }
				  String mDataProp_ = mDataProp + "_"+ column;
				  mDataProp_ = request.getParameter(mDataProp_);
				  if(null!=mDataProp_){
					  sort = (JUtil.camelToUnderline(mDataProp_) + " ")+(( null == requestParameters.getsSortDir_0()?"":requestParameters.getsSortDir_0()));
				  }
				}
			}
			
			JSONArray array =null;
			//默认数据权限
			final String ownerQuerySql = requestParameters.getOwnerSql();
			//不加数据权限
			 array = service.listAccessTokenAndFkText(rec, sort, paging, new MapperCallBackAdapter(){
				public void doCriteria(Object obj) throws Exception{
					Criteria criteria = (Criteria)obj;
					MapperUtil.builderOwnerSqlCriteria(ownerQuerySql, criteria);
				    MapperUtil.builderCriteria(obj, AccessToken.class, requestParameters.getBeanProxy());
					}
				}, appendArray);
			//返回数据
			if(requestParameters.getComp() == 1){
				if(requestParameters.getIsNonPage()==0){
					return new NormalDatagrid(paging.getCount(), array);
				}
				return new NormalDatagrid(0, array);
			}else{
				if(requestParameters.getIsNonPage()==0){
					return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),paging.getCount(),paging.getCount(), array));
				}
				return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),0,0, array));
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return setFail(""+e.getMessage());
		}
	}

	/**
	 * EXCEL 导出
	 * @param requestParameters
	 * @return
	 */
	@RequestMapping(value = "excelOut")
	@ResponseBody
	public Object excelOut(@ModelAttribute final  RequestParameters requestParameters,HttpServletRequest request,HttpServletResponse response) {
		try {
			AccessToken rec = new AccessToken();
			Page paging = null;
			if (requestParameters.getIsAllOut() == 0) {
			if(requestParameters.getComp() == 1){
				 paging = Page.getInstance(requestParameters.getPage()-1,requestParameters.getRows());
			}else{
				 paging = Page.getInstance_(requestParameters.getiDisplayStart(),requestParameters.getiDisplayLength());
			}
			}
			String sort = requestParameters.getSort();
			if(requestParameters.getComp() != 1){
				if(null != requestParameters.getiSortCol_0()){
				  int column = JUtil.strToInt(requestParameters.getiSortCol_0(), 0);
				  if(column < 0){
					  column = 0;
				  }
				  String mDataProp_ = mDataProp + "_"+ column;
				  mDataProp_ = request.getParameter(mDataProp_);
				  if(null!=mDataProp_){
					  sort = (JUtil.camelToUnderline(mDataProp_) + " ")+(( null == requestParameters.getsSortDir_0()?"":requestParameters.getsSortDir_0()));
				  }
				}
			}
			
			final String ownerQuerySql = requestParameters.getOwnerSql();
			List<AccessToken> list = service.listAccessToken(rec, sort, paging,
					new MapperCallBackAdapter() {
				@Override
				public void doCriteria(Object obj) throws Exception {
				    Criteria criteria = (Criteria)obj;
					MapperUtil.builderOwnerSqlCriteria(ownerQuerySql, criteria);
					MapperUtil.builderCriteria(obj, AccessToken.class,requestParameters.getBeanProxy());
				}
			});
			String result = urExcelOptionService.excelOut(list,templateFile,AccessToken.class,request,response);
			if (null == result) {
				return setSuccess("导出成功!");
			}
			return setFail(result);
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
			return setException("导出异常",e.getMessage());
		}
	}
	
	/**
	 * 模板导出
	 * @return
	 */
	@RequestMapping(value = "modelLoad")
	@ResponseBody
	public Object modelLoad(HttpServletRequest request,HttpServletResponse response) {
		try {
			String result = urExcelOptionService.excelModelOut(templateModelFile,request,response);
			if (null == result) {
				return setSuccess("导出成功!");
			}
			return setFail("fail",result);
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
			return setException("导出异常",e.getMessage());
		}
	}

	/**
	 * 修改上传
	 * @return
	 * @Description:
	 */
	@RequestMapping(value = "excelInput")
	@ResponseBody
	public Object excelInput(@ModelAttribute MultipartFile[] myfiles,HttpServletRequest request) {
		try {
			if(null == myfiles || myfiles.length == 0 ){
				return setFail("上传文件为空!");
			}
			MultipartFile myfile = myfiles[0];
			if(myfile.isEmpty()){
				return setFail("文件未上传!");
			}

			Map<String,Object> result = urExcelOptionService.getObjectListFromExcel(myfile.getInputStream(), AccessToken.class,new UrExcelCallBack(){
				public void callBack(List<String[]> excelList,Map<String,Object> resultMap,Method[] fieldMethod,Class[] fieldTypes,UrExcelOptionService us)
						throws Exception {
					/*
					 * 采用回调模式可以加入当前Controller的特殊处理代码适配原共有公共方法
					 */
					int i,length = excelList.size();

					if(excelList.size()>CommonConstants.LIMITIPUT){
						throw new Exception("导入行数超过"+CommonConstants.LIMITIPUT+" 请修改!");
					}
					if(length<=1){
						throw new Exception("导入行数至少需要4行 请修改!");
					}
					resultMap.put(CommonConstants.INPUT_RESULTKEY, null);
				}
			});
			//插入
            this.service.inputExcelData(result);
			// 处理批量上传
			List<AccessToken> dataErrList = (List<AccessToken>)result.get(CommonConstants.INPUT_LIST_SIGN_ERROR);
			if(null!=dataErrList && !dataErrList.isEmpty()){
				//需要返回错误数据
				String sign = JUtil.uuid12();
				SystemUtil.getInstance().setErrMap(sign,dataErrList);
				log.info("上传失败数据量："+dataErrList.size() + " 存入内存的标示："+sign);
				return setSuccess("上传成功!", sign);
			}
			log.info("全部上传成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return setException("上传异常!",e.getMessage());
		}
		return setSuccess("上传成功!");
	}


	/**
	 * 主键查找
	 * @return
	 */
	@RequestMapping(value = "findByPk")
	@ResponseBody
	public Object findByPk(@ModelAttribute final  RequestParameters requestParameters) {
		try {
			if(StringUtils.isEmpty(requestParameters.getPks())){
				return  setFail("主键参数为空!");
			}
			 FieldAppendArray appendArray = new FieldAppendArray();
			AccessToken rec = new AccessToken();
			 rec.setUserId(JUtil.strToInt(requestParameters.getPks()));
	         JSONObject obj = service.findAccessTokenAndFkText(rec, new MapperCallBackAdapter(), appendArray);
			return obj;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return setException("查询异常", e.getMessage());
		}
	}

	/**
	 * 模糊查找一个
	 * @return
	 */
	@RequestMapping(value = "find")
	@ResponseBody
	public Object find(@ModelAttribute AccessToken  record) {
		try {
			FieldAppendArray appendArray = new FieldAppendArray();
            JSONObject obj = service.findAccessTokenAndFkText(record, null, appendArray);
            return obj;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return setException("查询异常", e.getMessage());
		}
	}


  /**
	 *根据主键查找
	 * @return
	 */
	@RequestMapping(value = "listByPk")
	@ResponseBody
	public Object listByPk(@ModelAttribute final  RequestParameters requestParameters,HttpServletRequest request) {
		try {
			FieldAppendArray appendArray = new FieldAppendArray();
			AccessToken rec = new AccessToken();
			Page paging = null;
			if(requestParameters.getIsNonPage()==0){
			if(requestParameters.getComp() == 1){
				 paging = Page.getInstance(requestParameters.getPage()-1,requestParameters.getRows());
			}else{
				 paging = Page.getInstance_(requestParameters.getiDisplayStart(),requestParameters.getiDisplayLength());
			}
			}
			String sort = requestParameters.getSort();
			if(requestParameters.getComp() != 1){
				if(null != requestParameters.getiSortCol_0()){
				  int column = JUtil.strToInt(requestParameters.getiSortCol_0(), 0);
				  if(column < 0){
					  column = 0;
				  }
				  String mDataProp_ = mDataProp + "_"+ column;
				  mDataProp_ = request.getParameter(mDataProp_);
				  if(null!=mDataProp_){
					  sort = (JUtil.camelToUnderline(mDataProp_) + " ")+(( null == requestParameters.getsSortDir_0()?"":requestParameters.getsSortDir_0()));
				  }
				}
			}
			JSONArray array = service.listAccessTokenAndFkText(rec, sort, paging, new MapperCallBackAdapter(){
				public void doCriteria(Object obj) throws Exception {
					Criteria cri = (Criteria)obj;
					try {
						cri.andUserIdIn(JUtil.splitToListInteger(requestParameters.getPks()));
					} catch (Exception e) {
						log.error(e.getMessage(), e);
						throw e;
					}
				}
			}, appendArray);
		//返回数据
			if(requestParameters.getComp() == 1){
				if(requestParameters.getIsNonPage()==0){
					return new NormalDatagrid(paging.getCount(), array);
				}
				return new NormalDatagrid(0, array);
			}else{
				if(requestParameters.getIsNonPage()==0){
					return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),paging.getCount(),paging.getCount(), array));
				}
				return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),0,0, array));
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return setException("fail",e.getMessage());
		}
	}


	/**
	 * 物理删除
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "drop")
	@ResponseBody
	public Object drop(@ModelAttribute final  RequestParameters requestParameters){
		try {
			if(StringUtils.isEmpty(requestParameters.getPks())){
				return setFail("删除ID为空!");
			}
			service.dropAccessToken(requestParameters.getPks());
			return setSuccess("success");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return setException("fail",e.getMessage());
		}
	}

}
